#include <config.h>
#include <input_manager.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <draw.h>
#include <linux/input.h>
#include <unistd.h>


static int giXres;
static int giYres;
static int touch_fd;
static T_InputOpr g_tTouchScreenOpr;

static int TouchScreenDevInit(void)
{
	touch_fd = open("/dev/input/event0",O_RDONLY);
	if(touch_fd < 0)
	{
		printf("%s: open TOUCH_DEVICE_NAME fild\n ",__func__);
		return -1;
	}
	if (GetDispResolution(&giXres,&giYres))
	{
		return -1;
	}
	g_tTouchScreenOpr.iFd = touch_fd ;
	return 0 ;
}

static int TouchScreenDevExit(void)
{
	close(touch_fd);
	return 0 ;
}


static int itisoutoftime(struct timeval * tPreTime,struct timeval * tNowTime)
{
	int iPreMs;
	int iNowMs;
	iNowMs = tNowTime->tv_usec / 1000 + tNowTime->tv_sec * 1000 ;
	iPreMs = tPreTime->tv_usec / 1000 + tPreTime->tv_sec * 1000 ;

	return (iNowMs > iPreMs + 500 );
}

static int TouchScreenGetInputEvent(PT_InputEvent ptInputEvent)
{
	static struct timeval tPreTime;
	struct input_event ev;
	int iError;
	iError = read(touch_fd, &ev, sizeof(struct input_event));
	if (iError < (int)sizeof(struct input_event))
	{
		printf("read  error \n");
		return -1;
	}

	if(itisoutoftime(&tPreTime,&ev.time))
	{
		/*处理数据*/
		tPreTime =  ev.time;
		ptInputEvent->tTime = ev.time;
		ptInputEvent->iType = INPUT_TYPE_TOUCHSCREEN;
		if (EV_ABS==ev.type)
		{
			if(0x35 == ev.code) // ABS_MT_POSITION_X 
			{
				if(ev.value < giXres/3 )
				{
					ptInputEvent->iVal = INPUT_VALUE_UP;
				}
				else if (ev.value > giXres*2/3 )
				{
					ptInputEvent->iVal = INPUT_VALUE_DOWN;
				}
				else
				{
					ptInputEvent->iVal = INPUT_VALUE_UNKNOWN;
				}
				return 0;
			}
		}
	}
	else
	{
		return -1;
	}
	return 0;
}


static T_InputOpr g_tTouchScreenOpr = {
	.name          = "touchscreen",
	.DeviceInit    = TouchScreenDevInit,
	.DeviceExit    = TouchScreenDevExit,
	.GetInputEvent = TouchScreenGetInputEvent,
};

int TouchScreenInit(void)
{
	return RegisterInputOpr(&g_tTouchScreenOpr);
}

